package com.ajhlp.app.phoneDetailQuery.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import com.ajhlp.app.phoneDetailQuery.db.PhoneRuleDao;
import com.ajhlp.app.phoneDetailQuery.rule.IRuleParser;
import com.ajhlp.app.phoneDetailQuery.rule.Rule;
import com.ajhlp.app.phoneDetailQuery.rule.RuleQueryCondition;

@Transactional
public class PhoneRuleServiceImpl implements IPhoneRuleService {
	
	private Logger log = Logger.getLogger(getClass());
	
	private PhoneRuleDao dao;
	

	public PhoneRuleDao getDao() {
		return dao;
	}

	public void setDao(PhoneRuleDao dao) {
		this.dao = dao;
	}
	
	@Resource
	private IRuleParser ruleParser;
	

	public IRuleParser getRuleParser() {
		return ruleParser;
	}

	public void setRuleParser(IRuleParser ruleParser) {
		this.ruleParser = ruleParser;
	}

	public void saveRule(Rule rule) throws RuntimeException {
		// TODO Auto-generated method stub
		if(rule.getRule() != null){
			rule.setRule(rule.getRule().toUpperCase());
		}
		
		try {
			rule.setRegulation(JsonUtil.converObjToJson(ruleParser.parse(rule)));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("生成规则json串错误",e);
		}
		
		dao.saveRule(rule);
	}

	public void updateRule(Rule rule) throws RuntimeException {
		// TODO Auto-generated method stub
		dao.updateRule(rule);
	}

	public void deleteRule(String rule) throws RuntimeException {
		// TODO Auto-generated method stub
		Rule r = new Rule(rule, 0, null, null);
		dao.deleteRule(r);
	}

	public List<Rule> searchRule(RuleQueryCondition condition)
			throws RuntimeException {
		// TODO Auto-generated method stub
		if(!"asc".equals(condition.getOrder()) && !"desc".equals(condition.getOrder())){
			condition.setOrder("asc");
		}
		
		if(!"rule".equals(condition.getOrderColumn()) && !"price".equals(condition.getOrderColumn())){
			condition.setOrderColumn("price");
		}
		
		if(condition.getRule() != null){
			condition.setRule(condition.getRule().toUpperCase());
		}
		
		if("".equals(condition.getRule_fuzzy())){
			
		}
		
		if(condition.getRule_fuzzy() != null && !"".equals(condition.getRule_fuzzy().trim())){
			condition.setRule_fuzzy(condition.getRule_fuzzy().trim().toUpperCase()+"%");
		}else{
			condition.setRule_fuzzy(null);
		}
		
		return dao.searchRule(condition);
	}

}
